"""
ConnLLM - 统一的LLM适配层
为各种LLM提供商提供统一的接口
"""
from typing import Dict, List, Optional, Any, Generator
import importlib.metadata

try:
    __version__ = importlib.metadata.version("connllm")
except importlib.metadata.PackageNotFoundError:
    __version__ = "0.1.0.dev"

# 从核心模块导入
from .core.provider import LLMProvider, ProviderFactory, BaseProvider, RemoteProvider, LocalProvider
from .core.config import ConfigManager, DEFAULT_CONFIG, PREDEFINED_CONFIGS
from .core.keys import KeyManager
from .core.pricing import PricingManager, get_pricing_manager
from .core.exceptions import (
	LLMException, ConfigurationError, ProviderError, AuthenticationError,
	QuotaExceededError, RateLimitError, ConnectionError, TimeoutError,
	ServerError, InvalidRequestError, ContentFilterError, ModelNotFoundError,
	InputTooLongError, ProviderUnavailableError, UnsupportedOperationError,
	map_provider_error
)
from . import utils
from .utils import (
	rate_limit, provider_rate_limit, 
	mask_sensitive_text, mask_sensitive_fields, setup_secure_logging
)

# 导入V2架构组件
from .core_v2.interfaces import IProvider
from .core_v2.provider import BaseProviderV2
from .core_v2.capability import (
    Capability, CapabilityManagerV2, ModelCapability, ModelCapabilityManagerV2
)
from .core_v2.config import ConfigManagerV2
from .core_v2.http import HTTPClientV2
from .core_v2.processors import (
    RequestProcessor, ToolCallProcessor, WebSearchProcessor, ThinkingProcessor
)
from .providers import MoonshotProviderV2, OpenRouterProviderV2
from .api import ConnLLM, ChatAPI

# 导出主要类和函数
__all__ = [
    # 包版本
    "__version__",
    
    # 提供商类
    "LLMProvider",
    "ProviderFactory",
    "BaseProvider",
    "RemoteProvider",
    "LocalProvider",
    
    # 管理器类
    "ConfigManager",
    "KeyManager",
    "PricingManager",
    
    # 主要函数
    "create_provider",
    "complete",
    "complete_stream",
    "get_pricing_manager",
    
    # 异常类
    "LLMException",
    "ConfigurationError",
    "ProviderError",
    "AuthenticationError",
    "QuotaExceededError",
    "RateLimitError",
    "ConnectionError",
    "TimeoutError",
    "ServerError",
    "InvalidRequestError",
    "ContentFilterError",
    "ModelNotFoundError",
    "InputTooLongError",
    "ProviderUnavailableError",
    "UnsupportedOperationError",
    "map_provider_error",
    
    # 工具模块
    "utils",
    "rate_limit",
    "provider_rate_limit",
    "mask_sensitive_text",
    "mask_sensitive_fields",
    "setup_secure_logging",
    
    # V2架构组件
    "IProvider",
    "BaseProviderV2",
    "Capability",
    "CapabilityManagerV2",
    "ModelCapability",
    "ModelCapabilityManagerV2",
    "ConfigManagerV2",
    "HTTPClientV2",
    "RequestProcessor",
    "ToolCallProcessor",
    "WebSearchProcessor",
    "ThinkingProcessor",
    "MoonshotProviderV2",
    "OpenRouterProviderV2",
    "ConnLLM",
    "ChatAPI"
]

# 全局配置管理器
_config_manager = ConfigManager()

# 全局密钥管理器
_key_manager = KeyManager()


def create_provider(config_name: str = "default", overrides: Optional[Dict[str, Any]] = None) -> LLMProvider:
    """
    创建LLM提供商实例
    
    Args:
        config_name: 配置名称
        overrides: 覆盖配置的字典
        
    Returns:
        LLMProvider实例
    """
    # 获取配置
    config = _config_manager.get_config(config_name, overrides)
    
    # 获取提供商类型
    provider_type = config.get("provider", "anthropic")
    
    # 如果配置中没有API密钥，尝试从密钥管理器获取
    if not config.get("api_key") and not ProviderFactory.is_local_provider(provider_type):
        config["api_key"] = _key_manager.get_key(provider_type)
        
    # 创建提供商实例
    return ProviderFactory.create(config)


def complete(messages: List[Dict[str, str]], config_name: str = "default", 
             overrides: Optional[Dict[str, Any]] = None, stream: bool = False) -> str:
    """
    获取LLM完成
    
    Args:
        messages: 消息列表
        config_name: 配置名称
        overrides: 覆盖配置的字典
        stream: 是否使用流式响应
        
    Returns:
        完成的文本
    """
    provider = create_provider(config_name, overrides)
    return provider.complete(messages, stream)


def complete_stream(messages: List[Dict[str, str]], config_name: str = "default",
                   overrides: Optional[Dict[str, Any]] = None) -> Generator[str, None, None]:
    """
    获取LLM流式完成
    
    Args:
        messages: 消息列表
        config_name: 配置名称
        overrides: 覆盖配置的字典
        
    Returns:
        流式响应生成器
    """
    provider = create_provider(config_name, overrides)
    return provider.complete_stream(messages)


# 初始化全局管理器完成

# 配置安全日志
try:
	# 尝试配置安全日志过滤
	setup_secure_logging()
except Exception as e:
	import logging
	logging.getLogger("connllm").warning(f"配置安全日志失败: {str(e)}")
